package cn.iocoder.yudao.module.trade.service.giftcard;

import cn.iocoder.yudao.framework.common.enums.TerminalEnum;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.member.api.address.MemberAddressApi;
import cn.iocoder.yudao.module.member.api.address.dto.MemberAddressRespDTO;
import cn.iocoder.yudao.module.pay.api.order.PayOrderApi;
import cn.iocoder.yudao.module.pay.api.order.dto.PayOrderRespDTO;
import cn.iocoder.yudao.module.pay.api.shipping.WeChatApi;
import cn.iocoder.yudao.module.pay.api.shipping.dto.OrderKeyDTO;
import cn.iocoder.yudao.module.pay.api.shipping.dto.PayerDTO;
import cn.iocoder.yudao.module.pay.api.shipping.dto.ShippingDTO;
import cn.iocoder.yudao.module.pay.api.shipping.dto.WxDeliverGoodsDTO;
import cn.iocoder.yudao.module.pay.controller.admin.order.vo.PayOrderSubmitRespVO;
import cn.iocoder.yudao.module.pay.controller.app.order.vo.AppPayOrderSubmitReqVO;
import cn.iocoder.yudao.module.pay.dal.dataobject.wallet.PayWalletDO;
import cn.iocoder.yudao.module.pay.enums.wallet.PayWalletBizTypeEnum;
import cn.iocoder.yudao.module.pay.service.order.PayOrderService;
import cn.iocoder.yudao.module.pay.service.wallet.PayWalletService;
import cn.iocoder.yudao.module.pay.service.wallet.PayWalletTransactionService;
import cn.iocoder.yudao.module.pay.service.wallet.bo.WalletTransactionCreateReqBO;
import cn.iocoder.yudao.module.product.api.sku.ProductSkuApi;
import cn.iocoder.yudao.module.product.api.sku.dto.ProductSkuRespDTO;
import cn.iocoder.yudao.module.system.api.social.SocialUserApi;
import cn.iocoder.yudao.module.system.api.social.dto.SocialUserRespDTO;
import cn.iocoder.yudao.module.trade.controller.admin.giftcard.vo.CardPageReqVO;
import cn.iocoder.yudao.module.trade.controller.admin.giftcard.vo.CardSaveReqVO;
import cn.iocoder.yudao.module.trade.controller.app.giftcard.vo.*;
import cn.iocoder.yudao.module.trade.controller.app.order.vo.AppTradeOrderGiftCardCreateReqVO;
import cn.iocoder.yudao.module.trade.dal.dataobject.giftcard.*;
import cn.iocoder.yudao.module.trade.dal.dataobject.order.TradeOrderDO;
import cn.iocoder.yudao.module.trade.dal.dataobject.order.TradeOrderItemDO;
import cn.iocoder.yudao.module.trade.dal.mysql.giftcard.GiftCardMapper;
import cn.iocoder.yudao.module.trade.dal.mysql.order.TradeOrderItemMapper;
import cn.iocoder.yudao.module.trade.enums.ErrorCodeConstants;
import cn.iocoder.yudao.module.trade.enums.delivery.DeliveryTypeEnum;
import cn.iocoder.yudao.module.trade.enums.giftcard.GiftCardGroupTypeEnum;
import cn.iocoder.yudao.module.trade.enums.giftcard.GiftCardStatusEnum;
import cn.iocoder.yudao.module.trade.service.order.TradeOrderQueryService;
import cn.iocoder.yudao.module.trade.service.order.TradeOrderUpdateService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.servlet.ServletUtils.getClientIP;
import static cn.iocoder.yudao.module.trade.enums.ErrorCodeConstants.*;

@Service
public class GiftCardServiceImpl implements GiftCardService {

    @Resource
    private GiftCardMapper giftCardMapper;
    @Resource
    private GiftWxCardService giftWxCardService;
    @Resource
    private ProductSkuApi productSkuApi;
    @Resource
    @Lazy
    private TradeOrderUpdateService tradeOrderUpdateService;
    @Resource
    private TradeOrderQueryService tradeOrderQueryService;
    @Resource
    private GiftCardGroupService giftCardGroupService;
    @Resource
    private PayOrderService payOrderService;
    @Resource
    private GiftCardReceiveGiveService giftCardReceiveGiveService;
    @Resource
    private MemberAddressApi addressApi;
    @Resource
    private PayOrderApi payOrderApi;
    @Resource
    private GiftCardWalletLogService giftCardWalletLogService;
    @Resource
    private WeChatApi weChatApi;
    @Resource
    private TradeOrderItemMapper tradeOrderItemMapper;
    @Resource
    private SocialUserApi socialUserApi;
    @Resource
    private PayWalletTransactionService walletTransactionService;
    @Resource
    private PayWalletService payWalletService;


    /**
     * 撤销赠送礼品卡 与 领取礼品卡 操作互斥
     */
    static ReentrantLock giveReceiveLock = new ReentrantLock();

    @Override
    public AppGiftCardMemberVO queryMemberInfoByOpenId(String openid) {
        return giftCardMapper.queryMemberInfoByOpenId(openid);
    }

//    public static void main(String[] args) {
//        List<AppGiftCardSpuReqVO> appGiftCardSpuReqVOS1 = new ArrayList<>();
//        AppGiftCardSpuReqVO o = new AppGiftCardSpuReqVO();
//        o.setSkuId(7L);
//        o.setSpuId(11L);
//        o.setNum(1);
//        appGiftCardSpuReqVOS1.add(o);
//        AppGiftCardSpuReqVO o1 = new AppGiftCardSpuReqVO();
//        o1.setSkuId(8L);
//        o1.setSpuId(12L);
//        o1.setNum(1);
//        appGiftCardSpuReqVOS1.add(o1);
//        System.out.println(JSON.toJSONString(appGiftCardSpuReqVOS1));
////        JSON.toJSONString(appGiftCardSpuReqVOS1);
//        String giftCardSpuReq = JSON.toJSONString(appGiftCardSpuReqVOS1);
//        List<AppGiftCardSpuReqVO> appGiftCardSpuReqVOS = JSON.parseArray(giftCardSpuReq, AppGiftCardSpuReqVO.class);
//        System.out.println("appGiftCardSpuReqVOS:" + appGiftCardSpuReqVOS);
//    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PayOrderSubmitRespVO createGiftCardOrder(AppCreateGiftCardReqVO appCreateGiftCardReqVO) {
        //礼品卡微信
        GiftWxCardDO giftWxCardDO = giftWxCardService.selectByCardId(appCreateGiftCardReqVO.getWxCardId());
        if (null == giftWxCardDO) {
            throw exception(ErrorCodeConstants.GiftWxCardDO);
        }
        //member user信息
        AppGiftCardMemberVO appGiftCardMemberVO = queryMemberInfoByOpenId(appCreateGiftCardReqVO.getCreateOpenId());
        if (null == appGiftCardMemberVO) {
            throw exception(AppGiftCardMemberVO_NOT);
        }
        //礼品卡商品组合
        List<AppGiftCardGroupReqVO> giftCardGroupReqVOS = appCreateGiftCardReqVO.getGiftCardGroupReqVOS();
        GiftCardDO giftCardDO = new GiftCardDO();

        //所有商品组合内的商品
        List<AppTradeOrderGiftCardCreateReqVO.Item> items = new ArrayList<>();
        //所有商品组合内的价格
        Integer giftCardPrice = 0;

        //所有商品
        List<AppGiftCardSpuReqVO> allGiftCard = new ArrayList<>();

        for (AppGiftCardGroupReqVO y : giftCardGroupReqVOS) {
            //商品组合
            GiftCardGroupDO giftCardGroupDO = giftCardGroupService.selectById(y.getGiftCardGroupId());
            if (null == giftCardGroupDO) {
                throw exception(GiftCardGroupDO_NOT);
            }
            //获取礼品卡商品组合的商品
            String giftCardSpuReq = giftCardGroupDO.getGiftCardSpuReq();
            if (StringUtils.isNotBlank(giftCardSpuReq)) {
                List<AppGiftCardSpuReqVO> appGiftCardSpuReqVOS = JSON.parseArray(giftCardSpuReq, AppGiftCardSpuReqVO.class);
                //礼品卡商品总价
                giftCardPrice += giftCardGroupDO.getPrice();
                for (AppGiftCardSpuReqVO x : appGiftCardSpuReqVOS) {
                    AppTradeOrderGiftCardCreateReqVO.Item i = new AppTradeOrderGiftCardCreateReqVO.Item();
                    i.setSkuId(x.getSkuId());
                    i.setCount(x.getNum());
                    items.add(i);
                }
                allGiftCard.addAll(appGiftCardSpuReqVOS);
            }
        }

        //所有商品 判断库存 allGiftCard
        Map<Long, List<AppGiftCardSpuReqVO>> map = allGiftCard.stream().collect(Collectors.groupingBy(AppGiftCardSpuReqVO::getSkuId));
        map.forEach((k, v) -> {
            ProductSkuRespDTO productSkuRespDTO = productSkuApi.getSku(k);
            if (null == productSkuRespDTO) {
                throw exception(ProductSpuNOT);
            } else {
                Integer stock = productSkuRespDTO.getStock();
                int skuNum = v.stream().mapToInt(AppGiftCardSpuReqVO::getNum).sum();
                if (skuNum > stock) {
                    throw exception(ProductSpuNOT_stock);
                }
            }
        });

        //创建 交易订单 TradeOrder
        AppTradeOrderGiftCardCreateReqVO createReqVO = new AppTradeOrderGiftCardCreateReqVO();
        createReqVO.setRemark(appCreateGiftCardReqVO.getRemark());
        createReqVO.setDeliveryType(DeliveryTypeEnum.EXPRESS.getType());
        createReqVO.setItems(items);
        TradeOrderDO order = tradeOrderUpdateService.createOrderGiftCard
                (appGiftCardMemberVO.getUserId(), getClientIP(), createReqVO, TerminalEnum.WECHAT_MINI_PROGRAM.getTerminal(), giftCardPrice);
        //交易订单id
        Long tradeOrderId = order.getId();

        String giftCardGroup = JSON.toJSONString(giftCardGroupReqVOS);
        Long memberUserId = appGiftCardMemberVO.getUserId();
        Long socialUserId = appGiftCardMemberVO.getSocialUserId();
        appCreateGiftCardReqVO.setGroupType(1);
        giftCardDO = GiftCardDO.builder().giftCardTitle(giftWxCardDO.getBrandName())
                .giftCardPicUrl(giftWxCardDO.getBackgroundPicUrl())
                .wxCardId(appCreateGiftCardReqVO.getWxCardId())
                .blessings(appCreateGiftCardReqVO.getBlessings())
                .createMemberUserId(memberUserId)
                .createSocialUserId(socialUserId)
                .currentOwnerMemberUserId(memberUserId)
                .currentOwnerSocialUserId(socialUserId)
                .giftCardStatus(GiftCardStatusEnum.NO_USE.getType())
                .giftCardGroup(giftCardGroup)
                .giftCardPrice(giftCardPrice)
                .groupType(appCreateGiftCardReqVO.getGroupType())
                .tradeOrderId(tradeOrderId)
                .build();
        //创建礼品卡
        giftCardDO.setCreateTime(LocalDateTime.now());
        giftCardMapper.insert(giftCardDO);

        //提交订单
        AppPayOrderSubmitReqVO reqVO = new AppPayOrderSubmitReqVO();
        BeanUtils.copyProperties(appCreateGiftCardReqVO, reqVO);
        reqVO.setId(payOrderApi.selectByMerchantOrderId(tradeOrderId));
        PayOrderSubmitRespVO payOrderSubmitRespVO = payOrderService.submitOrder(reqVO, getClientIP());
        payOrderSubmitRespVO.setGiftCardId(giftCardDO.getId());
        return payOrderSubmitRespVO;
    }

    @Override
    public PayOrderSubmitRespVO notGiftCardOrder(AppGiftCardNotPayVO appGiftCardNotPayVO) {
        GiftCardDO giftCardDO = giftCardMapper.selectById(appGiftCardNotPayVO.getCardId());
        if (null == giftCardDO) {
            throw exception(GiftWxCardDO);
        }
        //提交订单
        AppPayOrderSubmitReqVO reqVO = new AppPayOrderSubmitReqVO();
        BeanUtils.copyProperties(appGiftCardNotPayVO, reqVO);
        reqVO.setId(payOrderApi.selectByMerchantOrderId(giftCardDO.getTradeOrderId()));
        return payOrderService.submitOrder(reqVO, getClientIP());
    }

    @Override
    public JSONObject detailGiftCardByCardId(Long cardId) {
        JSONObject jsonObject = new JSONObject();
        GiftCardDO giftCardDO = giftCardMapper.selectById(cardId);
        if (null == giftCardDO) {
            throw exception(GiftWxCardDO);
        }
        String giftCardGroup = giftCardDO.getGiftCardGroup();
        if (null == giftCardGroup) {
            throw exception(GiftCardGroupDO_NOT);
        }
        List<AppGiftCardGroupReqVO> appGiftCardSpuReqVOS = JSON.parseArray(giftCardGroup, AppGiftCardGroupReqVO.class);
        JSONArray jsonArray = new JSONArray();
        for (AppGiftCardGroupReqVO appGiftCardGroupReqVO : appGiftCardSpuReqVOS) {
            GiftCardGroupDO giftCardGroupDO = giftCardGroupService.selectById(appGiftCardGroupReqVO.getGiftCardGroupId());
            if (null == giftCardGroupDO) {
                throw exception(GiftCardGroupDO_NOT);
            }
            JSONObject j = new JSONObject();
            j.put("giftCardGroupDO", giftCardGroupDO);
            j.put("num", appGiftCardGroupReqVO.getNum());
            jsonArray.add(j);
        }
        jsonObject.put("giftCardDO", giftCardDO);
        jsonObject.put("appGiftCardSpuReqVOS", jsonArray);
        return jsonObject;
    }

    @Override
    public List<AppGiftCardUseListVO> queryGiftCardByStatus(Integer status, String openId) {
        List<AppGiftCardUseListVO> appGiftCardUseListVOS = new ArrayList<>();
        List<GiftCardDO> giftCardDOS = new ArrayList<>();
        AppGiftCardMemberVO appGiftCardMemberVO = queryMemberInfoByOpenId(openId);
        if (null == appGiftCardMemberVO) {
            throw exception(AppGiftCardMemberVO_NOT);
        }
        Long memberUserId = appGiftCardMemberVO.getUserId();
        if (status == -1) {
            List<AppGiftCardUseListVO> all = new ArrayList<>();
            giftCardDOS = giftCardMapper.queryGiftCardByStatusMapper(null, memberUserId);
            List<GiftCardReceiveGiveDO> giftCardReceiveGiveDOS = giftCardReceiveGiveService.queryGiftCardReceiveGiver(memberUserId);
            giftCardReceiveGiveDOS.forEach(x -> {
                GiftCardDO giftCardDO = this.giftCardMapper.selectById(x.getGiftCardId());
                giftCardDO.setGiftCardStatus(GiftCardStatusEnum.IS_RECEIVE.getType());
                all.add(new AppGiftCardUseListVO(giftCardDO, x.getGiveTime(), giftCardReceiveGiveService));
            });
            all.addAll(giftCardDOS.stream().map(m -> new AppGiftCardUseListVO(m, null, giftCardReceiveGiveService)).collect(Collectors.toList()));
            return all;
        }
        //可使用 赠送中 不可用
        if (GiftCardStatusEnum.CAN_USE.getType().equals(status)
                || GiftCardStatusEnum.IN_RECEIVE.getType().equals(status)
                || GiftCardStatusEnum.NO_USE.getType().equals(status)) {
            giftCardDOS = giftCardMapper.queryGiftCardByStatusMapper(status, memberUserId);
            return giftCardDOS.stream().map(m -> new AppGiftCardUseListVO(m, null, giftCardReceiveGiveService)).collect(Collectors.toList());
        } else if (GiftCardStatusEnum.IS_RECEIVE.getType().equals(status)) {
            //已赠送
            List<GiftCardReceiveGiveDO> giftCardReceiveGiveDOS = giftCardReceiveGiveService.queryGiftCardReceiveGiver(memberUserId);
            giftCardReceiveGiveDOS.forEach(x -> {
                GiftCardDO giftCardDO = this.giftCardMapper.selectById(x.getGiftCardId());
                giftCardDO.setGiftCardStatus(GiftCardStatusEnum.IS_RECEIVE.getType());
                appGiftCardUseListVOS.add(new AppGiftCardUseListVO(giftCardDO, x.getGiveTime(), giftCardReceiveGiveService));
            });
        }
        return appGiftCardUseListVOS;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer receiveGiftCard(Long cardId, String nickName, String avatar) {
        GiftCardDO giftCardDO = giftCardMapper.selectById(cardId);
        if (null == giftCardDO) {
            throw exception(GiftWxCardDO);
        }
        if (!giftCardDO.getGiftCardStatus().equals(GiftCardStatusEnum.CAN_USE.getType())) {
            throw exception(GiftWxCardDO_NOTUSR);
        }
        giftCardDO.setGiftCardStatus(GiftCardStatusEnum.IN_RECEIVE.getType());
        giftCardMapper.updateByIdAndStatus(cardId, giftCardDO, GiftCardStatusEnum.CAN_USE.getType());

        GiftCardReceiveGiveDO giftCardReceiveGive = new GiftCardReceiveGiveDO();
        giftCardReceiveGive.setGiftCardId(cardId);
        giftCardReceiveGive.setReceiveMemberUserId(giftCardDO.getCurrentOwnerMemberUserId());
        giftCardReceiveGive.setReceiveSocialUserId(giftCardDO.getCurrentOwnerSocialUserId());
        giftCardReceiveGive.setReceiveNickName(nickName);
        giftCardReceiveGive.setReceiveAvatar(avatar);
        giftCardReceiveGiveService.saveOrUpdateGiftCardReceiveGiveDO(giftCardReceiveGive);
        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer giveGiftCard(Long cardId, String openId, String nickName, String avatar) {
        giveReceiveLock.lock();
        try {
            GiftCardDO giftCardDO = giftCardMapper.selectById(cardId);
            if (null == giftCardDO) {
                throw exception(GiftWxCardDO);
            }

            if (!giftCardDO.getGiftCardStatus().equals(GiftCardStatusEnum.IN_RECEIVE.getType())) {
                throw exception(GiftWxCardDO_IN_RECEIVE);
            }
            List<GiftCardReceiveGiveDO> giftCardReceiveGiveDOS = giftCardReceiveGiveService.queryGiftCardReceiveGiverTime(cardId);
            if (null == giftCardReceiveGiveDOS || giftCardReceiveGiveDOS.isEmpty()) {
                throw exception(giftCardReceiveGiveDOS_not);
            }
            AppGiftCardMemberVO appGiftCardMemberVO = queryMemberInfoByOpenId(openId);
            if (null == appGiftCardMemberVO) {
                throw exception(AppGiftCardMemberVO_NOT);
            }
            Long userId = appGiftCardMemberVO.getUserId();
            Long socialUserId = giftCardMapper.querySocialUserIdByUserId(userId);
            Integer groupType = giftCardDO.getGroupType();
//            if (null != groupType) {
//                //储值卡
//                if (groupType.equals(GiftCardGroupTypeEnum.STORED_CARD.getType())) {
//                    //添加 钱包余额
//                    int walletBalance = 0;
//                    String giftCardGroup = giftCardDO.getGiftCardGroup();
//                    if (StringUtils.isNotBlank(giftCardGroup)) {
//                        List<AppGiftCardGroupReqVO> appGiftCardSpuReqVOS = JSON.parseArray(giftCardGroup, AppGiftCardGroupReqVO.class);
//                        if (null != appGiftCardSpuReqVOS && !appGiftCardSpuReqVOS.isEmpty()) {
//                            GiftCardGroupDO giftCardGroupDO = null;
//                            for (AppGiftCardGroupReqVO x : appGiftCardSpuReqVOS) {
//                                giftCardGroupDO = giftCardGroupService.selectById(x.getGiftCardGroupId());
//                                if (null != giftCardGroupDO) {
//                                    if (giftCardGroupDO.getGroupType().equals(GiftCardGroupTypeEnum.STORED_CARD.getType())) {
//                                        //分
//                                        walletBalance = giftCardGroupDO.getPrice() * x.getNum() * 100;
//                                    }
//                                }
//                            }
//                        }
//                    }
//                    //根据 userId 与 walletBalance 添加 钱包余额 pay_wallet表
//                    if (walletBalance > 0) {
//                        Integer balanceResult = giftCardMapper.addPayWalletBalanceByUserId(walletBalance, userId);
//                        if (balanceResult != 1) {
//                            throw exception(tradeOrderDO_Gift_CX1);
//                        } else {
//                            //记录 礼品卡-储蓄卡 充值记录
//                            GiftCardWalletLogDO giftCardWalletLogDO = new GiftCardWalletLogDO();
//                            giftCardWalletLogDO.setGiftCardId(giftCardDO.getId());
//                            giftCardWalletLogDO.setUserId(userId);
//                            giftCardWalletLogDO.setAddBalance(walletBalance);
//                            giftCardWalletLogDO.setCreateTime(LocalDateTime.now());
//                            giftCardWalletLogService.createGiftCardWalletLog(giftCardWalletLogDO);
//                        }
//                    }
//                }
//            }

            giftCardDO.setGiftCardStatus(GiftCardStatusEnum.CAN_USE.getType());
            giftCardDO.setCurrentOwnerMemberUserId(userId);
            giftCardDO.setCurrentOwnerSocialUserId(socialUserId);
            int result = giftCardMapper.updateByIdAndStatus(cardId, giftCardDO, GiftCardStatusEnum.IN_RECEIVE.getType());
            if (result != 1) {
                throw exception(tradeOrderDO_Gift);
            }

            GiftCardReceiveGiveDO giftCardReceiveGive = giftCardReceiveGiveDOS.get(0);
            giftCardReceiveGive.setGiveTime(new Date());
            giftCardReceiveGive.setGiveMemberUserId(userId);
            giftCardReceiveGive.setGiveSocialUserId(socialUserId);
            giftCardReceiveGive.setGiveNickName(nickName);
            giftCardReceiveGive.setGiveAvatar(avatar);
            giftCardReceiveGiveService.saveOrUpdateGiftCardReceiveGiveDO(giftCardReceiveGive);

            //领取成功 改变TradeOrder user_id
            tradeOrderUpdateService.updateUserIdByTradeOrderId(userId, giftCardDO.getTradeOrderId());

            Long tradeOrderId = giftCardDO.getTradeOrderId();
            Long updateResult = tradeOrderUpdateService.updateOrderCompleted(tradeOrderId);
            if (updateResult != 1) {
                throw exception(tradeOrderDO_Gift_CX112);
            }
        } finally {
            giveReceiveLock.unlock();
        }
        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer revokeGive(Long cardId) {
        giveReceiveLock.lock();
        try {
            GiftCardDO giftCardDO = giftCardMapper.selectById(cardId);
            if (null == giftCardDO) {
                throw exception(GiftWxCardDO);
            }
            giftCardDO.setGiftCardStatus(GiftCardStatusEnum.CAN_USE.getType());
            int result = giftCardMapper.updateByIdAndStatus(cardId, giftCardDO, GiftCardStatusEnum.IN_RECEIVE.getType());
            if (result != 1) {
                throw exception(tradeOrderDO_Gift_CX);
            }
            giftCardReceiveGiveService.deleteGiveReceiveByCardId(cardId);
        } finally {
            giveReceiveLock.unlock();
        }
        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer lisy(Long cardId, String openId) {
        GiftCardDO giftCardDO = giftCardMapper.selectById(cardId);
        if (null == giftCardDO) {
            throw exception(GiftWxCardDO);
        }
        if (!giftCardDO.getGiftCardStatus().equals(GiftCardStatusEnum.CAN_USE.getType())) {
            throw exception(GiftWxCardDO_IN_RECEIVE);
        }
        AppGiftCardMemberVO appGiftCardMemberVO = queryMemberInfoByOpenId(openId);
        if (null == appGiftCardMemberVO) {
            throw exception(AppGiftCardMemberVO_NOT);
        }
        Long userId = appGiftCardMemberVO.getUserId();
        Integer groupType = giftCardDO.getGroupType();
        if (null != groupType) {
            //储值卡
            if (groupType.equals(GiftCardGroupTypeEnum.STORED_CARD.getType())) {
                //添加 钱包余额
                int walletBalance = 0;
                String giftCardGroup = giftCardDO.getGiftCardGroup();
                if (StringUtils.isNotBlank(giftCardGroup)) {
                    List<AppGiftCardGroupReqVO> appGiftCardSpuReqVOS = JSON.parseArray(giftCardGroup, AppGiftCardGroupReqVO.class);
                    if (null != appGiftCardSpuReqVOS && !appGiftCardSpuReqVOS.isEmpty()) {
                        GiftCardGroupDO giftCardGroupDO = null;
                        for (AppGiftCardGroupReqVO x : appGiftCardSpuReqVOS) {
                            giftCardGroupDO = giftCardGroupService.selectById(x.getGiftCardGroupId());
                            if (null != giftCardGroupDO) {
                                if (giftCardGroupDO.getGroupType().equals(GiftCardGroupTypeEnum.STORED_CARD.getType())) {
                                    //分
                                    walletBalance = giftCardGroupDO.getActualAmount() * x.getNum() * 100;
                                }
                            }
                        }
                    }
                }
                //根据 userId 与 walletBalance 添加 钱包余额 pay_wallet表
                if (walletBalance > 0) {
                    PayWalletDO payWalletDO = payWalletService.getOrCreateWallet(userId, UserTypeEnum.MEMBER.getValue());
                    if (null == payWalletDO) {
                        throw exception(tradeOrderDO_Gift_CX123);
                    }
                    Integer balanceResult = giftCardMapper.addPayWalletBalanceByUserId(walletBalance, payWalletDO.getId());
                    if (balanceResult != 1) {
                        throw exception(tradeOrderDO_Gift_CX1);
                    } else {
                        //记录 礼品卡-储蓄卡 充值记录
                        GiftCardWalletLogDO giftCardWalletLogDO = new GiftCardWalletLogDO();
                        giftCardWalletLogDO.setGiftCardId(giftCardDO.getId());
                        giftCardWalletLogDO.setUserId(userId);
                        giftCardWalletLogDO.setAddBalance(walletBalance);
                        giftCardWalletLogDO.setCreateTime(LocalDateTime.now());
                        giftCardWalletLogService.createGiftCardWalletLog(giftCardWalletLogDO);

                        //生成钱包流水   PayWalletBizTypeEnum.RECHARGE 充值
                        WalletTransactionCreateReqBO transactionCreateReqBO = new WalletTransactionCreateReqBO()
                                .setWalletId(payWalletDO.getId()).setPrice(walletBalance).setBalance(payWalletDO.getBalance() + walletBalance)
                                .setBizId(String.valueOf(giftCardDO.getId()))
                                .setBizType(PayWalletBizTypeEnum.RECHARGE.getType()).setTitle(PayWalletBizTypeEnum.RECHARGE.getDescription());
                        walletTransactionService.createWalletTransaction(transactionCreateReqBO);
                    }
                }
            }
        }

        giftCardDO.setGiftCardStatus(GiftCardStatusEnum.NO_USE.getType());
        int result = giftCardMapper.updateByIdAndStatus(cardId, giftCardDO, GiftCardStatusEnum.CAN_USE.getType());
        if (result != 1) {
            throw exception(tradeOrderDO_Gift_CX);
        }

//        Long tradeOrderId = giftCardDO.getTradeOrderId();
//        Long updateResult = tradeOrderUpdateService.updateOrderCompleted(tradeOrderId);
//        if (updateResult != 1L) {
//            throw exception(tradeOrderDO_Gift_CX112);
//        }
        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer useGiveCard(Long cardId, Long addressId, String openId) {
        GiftCardDO giftCardDO = giftCardMapper.selectById(cardId);
        if (null == giftCardDO) {
            throw exception(GiftWxCardDO);
        }
        Long tradeOrderId = giftCardDO.getTradeOrderId();
        TradeOrderDO tradeOrderDO = tradeOrderQueryService.getOrder(tradeOrderId);
        if (null == tradeOrderDO) {
            throw exception(tradeOrderDO_not);
        }
        AppGiftCardMemberVO appGiftCardMemberVO = queryMemberInfoByOpenId(openId);
        if (null == appGiftCardMemberVO) {
            throw exception(AppGiftCardMemberVO_NOT);
        }
        Long userId = appGiftCardMemberVO.getUserId();
        MemberAddressRespDTO address = addressApi.getAddress(addressId, userId);
        cn.hutool.core.lang.Assert.notNull(address, "地址({}) 不能为空", addressId);
        tradeOrderDO.setReceiverName(address.getName()).setReceiverMobile(address.getMobile())
                .setReceiverAreaId(address.getAreaId()).setReceiverDetailAddress(address.getDetailAddress());
        //礼品卡订单使用状态 已使用
        tradeOrderUpdateService.updateTradeOrderGiftDO(tradeOrderDO);
        giftCardDO.setGiftCardStatus(GiftCardStatusEnum.NO_USE.getType());
        giftCardMapper.updateById(giftCardDO);
        return 1;
    }


    @Override
    public AppSomeVO giftCardReceiveGive(Long cardId) {
        GiftCardDO giftCardDO = giftCardMapper.selectById(cardId);
        if (null == giftCardDO) {
            throw exception(GiftWxCardDO);
        }
        return queryAppSomeVO(giftCardDO.getId());
    }


    @Override
    public Long createCard(CardSaveReqVO createReqVO) {
        // 插入
        GiftCardDO card = cn.iocoder.yudao.framework.common.util.object.BeanUtils.toBean(createReqVO, GiftCardDO.class);
        giftCardMapper.insert(card);
        // 返回
        return card.getId();
    }

    @Override
    public void updateCard(CardSaveReqVO updateReqVO) {
        // 校验存在
        validateCardExists(updateReqVO.getId());
        // 更新
        GiftCardDO updateObj = cn.iocoder.yudao.framework.common.util.object.BeanUtils.toBean(updateReqVO, GiftCardDO.class);
        giftCardMapper.updateById(updateObj);
    }

    @Override
    public void deleteCard(Long id) {
        // 校验存在
        validateCardExists(id);
        // 删除
        giftCardMapper.deleteById(id);
    }

    private void validateCardExists(Long id) {
        if (giftCardMapper.selectById(id) == null) {
            throw exception(GiftWxCardDO);
        }
    }

    @Override
    public GiftCardDO getCard(Long id) {
        return giftCardMapper.selectById(id);
    }

    @Override
    public PageResult<GiftCardDO> getCardPage(CardPageReqVO pageReqVO) {
        return giftCardMapper.selectPage(pageReqVO);
    }

    @Override
    public AppSomeVO queryAppSomeVO(Long giftCardId) {
        return giftCardMapper.queryAppSomeVO(giftCardId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateByTradeOrderId(Integer giftCardStatus, Long tradeOrderId, Integer changeType) {
        giftCardMapper.updateGiftCardByOrderId(giftCardStatus, tradeOrderId);
        if (changeType == 1){
            return;
        }

        // TODO: 2024/2/1 卡支付成功后 收货状态
        // 发货
        try {
            WxDeliverGoodsDTO vo = new WxDeliverGoodsDTO();
            OrderKeyDTO order_key = new OrderKeyDTO();
            order_key.setMchid("");
            order_key.setOrder_number_type(1);
            PayOrderRespDTO payOrder = payOrderApi.getOrderByMerchantOrderId(tradeOrderId);
            order_key.setOut_trade_no(payOrder.getNo());
            order_key.setTransaction_id("");
            List<GiftCardDO> giftCardDOS = giftCardMapper.queryGiftCardByTradeOrderId(tradeOrderId);
            if (null != giftCardDOS && !giftCardDOS.isEmpty()) {
                Long createMemberUserId = giftCardDOS.get(0).getCreateMemberUserId();
                PayerDTO payer = new PayerDTO();
                //获取openId
                SocialUserRespDTO socialUserByMemberUserId = socialUserApi.getSocialUserByMemberUserId(createMemberUserId);
                payer.setOpenid(socialUserByMemberUserId.getOpenid());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
                vo.setUpload_time(sdf.format(new Date()));
                vo.setPayer(payer);
                vo.setOrder_key(order_key);
                //虚拟商品
                vo.setLogistics_type(3);
                vo.setDelivery_mode(1);
                vo.setIs_all_delivered(false);
                List<ShippingDTO> shipping_list = new ArrayList<>();
                List<TradeOrderItemDO> tradeOrderItemList = tradeOrderItemMapper.selectListByOrderId(tradeOrderId);
                for (TradeOrderItemDO t : tradeOrderItemList) {
                    ShippingDTO shipping = new ShippingDTO();
                    shipping.setTracking_no(t.getLogisticsNo());
                    shipping.setItem_desc(t.getSpuName());
                    shipping_list.add(shipping);
                }
                vo.setShipping_list(shipping_list);
                weChatApi.uploadShippingInfo(vo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //改为已发货
        Long updateResult = tradeOrderUpdateService.updateOrderDelivered(tradeOrderId);
        if (updateResult != 1L) {
            throw exception(tradeOrderDO_Gift_CX112);
        }
    }

    @Override
    public boolean queryGiftCardByTradeOrderId(Long tradeOrderId) {
        List<GiftCardDO> giftCardDOS = giftCardMapper.queryGiftCardByTradeOrderId(tradeOrderId);
        if (null == giftCardDOS) {
            return true;
        }
        if (giftCardDOS.isEmpty()) {
            return true;
        }
        return giftCardDOS.get(0).getGiftCardStatus().equals(GiftCardStatusEnum.CAN_USE.getType());
    }

}
